
<template>
  <!-- // 分类参数 -->
  <div class="class-paramater main-box">
    <el-alert
      class="alert"
      title="注意：只允许为第三级分类设置相关参数"
      type="warning"
      show-icon
    >
    </el-alert>
    <div class="class-paramater-top">
      <span>选择商品分类：</span>
      <el-cascader
        class="cascader"
        clearable
        v-model="paramaterId"
        :props="props"
        :options="allParamaterList"
      >
      </el-cascader>
    </div>
    <div class="class-paramater-main fenye-top">
      <el-tabs value="first">
        <el-tab-pane label="动态参数" name="first">
          <el-button @click="addMany()" size="medium" type="primary"
            >添加参数</el-button
          >

          <!-- 参数表格 -->
          <el-table
            :stripe="true"
            :data="paramaterList"
            border
            style="width: 100%; margin-top: 15px"
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <el-tag
                  closable
                  class="tag-chi"
                  v-for="(ele, index) in row.attr_vals.split(',')"
                  type="success"
                  :key="index"
                  @close="handleClose(row, ele, index)"
                  >{{ ele }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  style="width: 150px"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              type="index"
              label="编号"
              width="50"
            >
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>

            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-button
                  @click="editParamater(row)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                ></el-button>
                <el-button
                  @click="deleteParamater(row)"
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="second">
          <el-button @click="addOnly()" size="medium" type="primary"
            >添加属性</el-button
          >

          <el-table
            :stripe="true"
            :data="paramaterOnlyLists"
            border
            style="width: 100%; margin-top: 15px"
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <el-tag
                  closable
                  class="tag-chi"
                  v-for="(ele, index) in row.attr_vals.split(',')"
                  v-show="ele !== ''"
                  type="success"
                  :key="index"
                  @close="handleClose(row, index)"
                  >{{ ele }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  style="width: 150px"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              type="index"
              label="编号"
              width="50"
            >
            </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>

            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-button
                  @click="editParamater(row)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                ></el-button>
                <el-button
                  @click="deleteParamater(row)"
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="tankuang">
      <!-- 添加参数、属性 -->
      <el-dialog
        :title="dialogStatus === 'many' ? '添加参数' : '添加属性'"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          :model="addParamater"
          :rules="rules"
          ref="addParamaterLog"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item autofocus="true" label="参数/属性名称" prop="attr_name">
            <el-input
              autofocus="true"
              v-model="addParamater.attr_name"
              placeholder="请输入参数/属性名称"
            ></el-input>
          </el-form-item>
          <el-form-item autofocus="true" label="具体项" prop="attr_vals">
            <el-input
              autofocus="true"
              v-model="addParamater.attr_vals"
              placeholder="请输入参数/属性具体项"
            ></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addAParamater()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑参数 -->
      <el-dialog
        :title="dialogStatus === 'many' ? '修改动态参数' : '修改静态属性'"
        :visible.sync="dialogFormVisible2"
      >
        <el-form
          :model="editParamaterInput"
          :rules="rules"
          ref="editParamaterLog"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item autofocus="true" label="参数/属性名称" prop="attr_name">
            <el-input
              autofocus="true"
              v-model="editParamaterInput.attr_name"
              placeholder="请输入参数/属性名称"
            ></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="editAParamater()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //修改参数input框
      editParamaterInput: {
        attr_name: "",
      },

      allParamaterList: null,
      paramaterId: [],
      paramaterList: null,
      paramaterOnlyLists: null,
      //列表包含子级的项
      props: {
        label: "cat_name",
        value: "cat_id",
        expandTrigger: "hover",
      },
      // 判断添加弹框状态
      dialogStatus: "many",
      dialogFormVisible: false,
      dialogFormVisible2: false,
      addParamater: {
        attr_name: "",
        attr_sel: "many",
        attr_vals: "",
      },
      rules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数/属性名称",
            trigger: "blur,change",
          },
        ],
        attr_vals: [
          {
            required: true,
            message: "请输入具体项",
            trigger: "blur,change",
          },
        ],
      },
      //动态添加标签
      inputVisible: false,
      inputValue: "",
    };
  },
  watch: {
    paramaterId(newValue, oldValue) {
      console.log(newValue);
      if (newValue !== oldValue) {
        if (newValue.length !== 3) {
          this.paramaterList = [];
          console.log("no 3");
        } else {
          console.log(newValue);
          this.getparamaterList(newValue[2]);
        }
      }
    },
  },
  methods: {
    //获取下拉列表内的树形结构
    async getAllParamater() {
      const res = await this.$axios.get("categories");
      this.allParamaterList = res.data.data;
    },

    async getparamaterList(id) {
      const res = await this.$axios.get(`categories/${id}/attributes?sel=many`);
      const resOnly = await this.$axios.get(
        `categories/${id}/attributes?sel=only`
      );
      this.paramaterList = res.data.data;
      this.paramaterOnlyLists = resOnly.data.data;
      console.log(this.paramaterOnlyLists);
    },

    //添加参数
    addOnly() {
      if (this.paramaterId.length === 3) {
        this.dialogFormVisible = true;
        this.dialogStatus = "only";
      } else {
        this.$message.error("请先选择商品分类");
      }
    },
    addMany() {
      if (this.paramaterId.length === 3) {
        this.dialogFormVisible = true;
        this.dialogStatus = "many";
      } else {
        this.$message.error("请先选择商品分类");
      }
    },
    //确认添加
    addAParamater() {
      this.$refs.addParamaterLog.validate(async (valid) => {
        if (valid) {
          this.addParamater.attr_sel = this.dialogStatus;
          // console.log(this.addParamater);
          const res = await this.$axios.post(
            `categories/${this.paramaterId[2]}/attributes`,
            this.addParamater
          );
          if (res.data.data.attr_sel === "many") {
            this.paramaterList.push(res.data.data);
          } else if (res.data.data.attr_sel === "only") {
            this.paramaterOnlyLists.push(res.data.data);
          }
          this.addParamater = {
            attr_name: "",
            attr_sel: "many",
            attr_vals: "",
          };
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.dialogFormVisible = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //删除参数
    deleteParamater(row) {
      console.log(row);
      this.$confirm("此操作将永久项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (row.attr_sel === "many") {
            const index = this.paramaterList.findIndex(
              (ele) => ele.attr_id === row.attr_id
            );
            this.paramaterList.splice(index, 1);
          } else {
            const index = this.paramaterOnlyLists.findIndex(
              (ele) => ele.attr_id === row.attr_id
            );
            this.paramaterOnlyLists.splice(index, 1);
          }
          const res = await this.$axios.delete(
            `categories/${row.cat_id}/attributes/${row.attr_id}`
          );
          console.log(res);

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改参数
    editParamater(row) {
      this.editParamaterInput = { ...row };
      this.dialogFormVisible2 = true;
      // console.log(row);
    },
    //编辑提交
    async putEdit() {
      const { attr_id, attr_name, attr_sel, attr_vals, cat_id } =
        this.editParamaterInput;
      const res = await this.$axios.put(
        `categories/${cat_id}/attributes/${attr_id}`,
        {
          attr_name,
          attr_sel,
          attr_vals,
        }
      );
      if (attr_sel === "many") {
        const index = this.paramaterList.findIndex(
          (ele) => ele.attr_id === attr_id
        );
        this.paramaterList[index] = res.data.data;
        this.paramaterList = [...this.paramaterList];
      } else {
        const index = this.paramaterOnlyLists.findIndex(
          (ele) => ele.attr_id === attr_id
        );
        this.paramaterOnlyLists[index] = res.data.data;
        this.paramaterOnlyLists = [...this.paramaterOnlyLists];
      }
    },
    editAParamater() {
      console.log(this.editParamaterInput);
      this.$refs.editParamaterLog.validate(async (valid) => {
        if (valid) {
          this.putEdit();
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.editParamaterInput = {
            attr_name: "",
          };
          this.dialogFormVisible2 = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //动态添加标签
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    async handleInputConfirm(row) {
      // this.editParamaterInput = { ...row };
      let { attr_id, attr_name, attr_sel, attr_vals, cat_id } = row;
      let inputValue = this.inputValue;
      if (inputValue) {
        row.attr_vals = attr_vals + "," + inputValue;
        await this.$axios.put(`categories/${cat_id}/attributes/${attr_id}`, {
          attr_name,
          attr_sel,
          attr_vals,
        });
      }
      this.inputVisible = false;
      this.inputValue = "";
    },

    //动态删除标签
    async handleClose(row, index) {
      // console.log(index);
      let { attr_id, cat_id } = row;
      let arr = row.attr_vals.split(",");
      arr.splice(index, 1);
      row.attr_vals = arr.join(",");
      const res = await this.$axios.put(
        `categories/${cat_id}/attributes/${attr_id}`,
        row
      );
    },
  },
  created() {
    this.getAllParamater();
  },
};
</script>

<style>
.el-scrollbar__wrap {
  height: 300px !important;
}
.cascader {
  width: 30% !important;
}
.alert {
  margin-bottom: 15px;
}
.tag-chi {
  margin-right: 15px;
}
</style>